<template>
  <div class="dashboard-panel">
    <!-- 顶部概览卡片 -->
    <el-row :gutter="20">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="overview-card user-card">
          <template #header>
            <div class="card-header">
              <el-icon><User /></el-icon>
              <span>用户总数</span>
            </div>
          </template>
          <div class="card-content">
            <div class="card-value">{{ dashboardData.userCount || 0 }}</div>
            <div class="card-info">
              <span>今日新增: </span>
              <span class="highlight">+{{ dashboardData.todayNewUsers || 0 }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="overview-card question-card">
          <template #header>
            <div class="card-header">
              <el-icon><QuestionFilled /></el-icon>
              <span>问题总数</span>
            </div>
          </template>
          <div class="card-content">
            <div class="card-value">{{ dashboardData.questionCount || 0 }}</div>
            <div class="card-info">
              <span>待审核: </span>
              <span class="highlight">{{ dashboardData.pendingQuestions || 0 }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="overview-card answer-card">
          <template #header>
            <div class="card-header">
              <el-icon><ChatDotRound /></el-icon>
              <span>回答总数</span>
            </div>
          </template>
          <div class="card-content">
            <div class="card-value">{{ dashboardData.answerCount || 0 }}</div>
            <div class="card-info">
              <span>采纳率: </span>
              <span class="highlight">{{ dashboardData.acceptRate || '0%' }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="overview-card visit-card">
          <template #header>
            <div class="card-header">
              <el-icon><View /></el-icon>
              <span>今日访问量</span>
            </div>
          </template>
          <div class="card-content">
            <div class="card-value">{{ dashboardData.todayVisits || 0 }}</div>
            <div class="card-info">
              <span>同比昨日: </span>
              <span class="highlight" :class="{'up': dashboardData.visitTrend > 0, 'down': dashboardData.visitTrend < 0}">
                {{ dashboardData.visitTrend > 0 ? '+' : '' }}{{ dashboardData.visitTrend || 0 }}%
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :xs="24" :lg="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>用户增长趋势</span>
              <el-select v-model="userChartPeriod" size="small" style="width: 120px">
                <el-option label="近7天" value="week"></el-option>
                <el-option label="近30天" value="month"></el-option>
                <el-option label="近一年" value="year"></el-option>
              </el-select>
            </div>
          </template>
          <div class="chart-container" id="userGrowthChart">
            <!-- Chart will be rendered here -->
            <div class="chart-placeholder" v-if="!chartRendered">
              <el-empty description="加载用户增长图表..."></el-empty>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :lg="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>内容分布</span>
            </div>
          </template>
          <div class="chart-container" id="contentDistributionChart">
            <!-- Chart will be rendered here -->
            <div class="chart-placeholder" v-if="!chartRendered">
              <el-empty description="加载内容分布图表..."></el-empty>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 待处理事项 -->
    <el-card shadow="hover" class="pending-tasks-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon><Warning /></el-icon>
            <span>待处理事项</span>
          </div>
          <el-button type="primary" size="small" @click="refreshDashboard">
            <el-icon><Refresh /></el-icon>刷新
          </el-button>
        </div>
      </template>
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12">
          <div class="task-group">
            <h4><el-icon><Warning /></el-icon> 待审核问题 ({{ dashboardData.pendingQuestions || 0 }})</h4>
            <div class="task-table-wrapper">
              <el-table
                :data="dashboardData.recentPendingQuestions || []"
                style="width: 100%"
                size="small"
                border
                stripe
                highlight-current-row
              >
                <el-table-column prop="title" label="标题" show-overflow-tooltip />
                <el-table-column prop="createTime" label="提交时间" width="180" />
                <el-table-column label="操作" width="120" fixed="right">
                  <template #default="scope">
                    <el-button type="primary" size="small" plain @click="handleQuickApprove(scope.row)">通过</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div class="task-footer" v-if="dashboardData.pendingQuestions > 0">
              <el-button type="primary" text @click="switchTab('pending')">查看全部 <el-icon class="el-icon--right"><ArrowRight /></el-icon></el-button>
            </div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="12">
          <div class="task-group">
            <h4><el-icon><Bell /></el-icon> 系统通知</h4>
            <div class="system-notification-timeline">
              <el-timeline>
                <el-timeline-item
                  v-for="(activity, index) in dashboardData.recentActivities || []"
                  :key="index"
                  :type="activity.type"
                  :timestamp="activity.time"
                  size="small"
                >
                  {{ activity.content }}
                </el-timeline-item>
              </el-timeline>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick, onBeforeUnmount } from 'vue';
import { ElMessage } from 'element-plus';
import { 
  User, 
  QuestionFilled, 
  ChatDotRound, 
  View, 
  Warning, 
  Bell, 
  Refresh,
  ArrowRight 
} from '@element-plus/icons-vue';
import { getDashboardData, reviewQuestion } from '../../api/admin';
// 引入完整的echarts库
import * as echarts from 'echarts';

const props = defineProps({
  // 可以接收一些初始数据
});

const emit = defineEmits(['switch-tab']);

// 图表实例
let userGrowthChart = null;
let contentDistributionChart = null;
let chartRendered = ref(false);

// 仪表盘数据
const dashboardData = ref({});
const userChartPeriod = ref('week');

// 切换到其他标签页
const switchTab = (tabName) => {
  emit('switch-tab', tabName);
};

// 刷新仪表盘数据
const refreshDashboard = async () => {
  try {
    // 从API获取仪表盘数据
    const response = await getDashboardData();
    dashboardData.value = response.data || {
      userCount: 0,
      todayNewUsers: 0,
      questionCount: 0,
      pendingQuestions: 0,
      answerCount: 0,
      acceptRate: '0%',
      todayVisits: 0,
      visitTrend: 0,
      recentPendingQuestions: [],
      recentActivities: []
    };
    
    // 等待DOM更新后初始化图表
    nextTick(() => {
      renderUserGrowthChart();
      renderContentDistributionChart();
      chartRendered.value = true;
    });
  } catch (error) {
    console.error('获取仪表盘数据失败:', error);
    ElMessage.error('获取仪表盘数据失败');
  }
};

// 渲染用户增长趋势图表
const renderUserGrowthChart = () => {
  const chartDom = document.getElementById('userGrowthChart');
  if (!chartDom) return;
  
  // 销毁已有实例
  if (userGrowthChart) {
    userGrowthChart.dispose();
  }
  
  // 创建图表实例
  userGrowthChart = echarts.init(chartDom);
  
  // 模拟数据
  let xData = [];
  let userData = [];
  
  // 根据选择的周期生成不同的数据
  if (userChartPeriod.value === 'week') {
    // 最近7天数据
    for (let i = 6; i >= 0; i--) {
      const date = new Date();
      date.setDate(date.getDate() - i);
      xData.push(`${date.getMonth() + 1}/${date.getDate()}`);
      userData.push(Math.floor(Math.random() * 50) + 10);
    }
  } else if (userChartPeriod.value === 'month') {
    // 最近30天数据，按周聚合
    for (let i = 0; i < 4; i++) {
      xData.push(`第${i + 1}周`);
      userData.push(Math.floor(Math.random() * 200) + 50);
    }
  } else if (userChartPeriod.value === 'year') {
    // 最近12个月数据
    const monthNames = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
    for (let i = 0; i < 12; i++) {
      xData.push(monthNames[i]);
      userData.push(Math.floor(Math.random() * 500) + 100);
    }
  }
  
  // 设置图表选项
  const option = {
    title: {
      text: '用户增长趋势',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: xData,
      axisLine: {
        lineStyle: {
          color: '#ddd'
        }
      },
      axisLabel: {
        color: '#666'
      }
    },
    yAxis: {
      type: 'value',
      name: '用户数',
      nameTextStyle: {
        color: '#666'
      },
      axisLine: {
        show: false
      },
      axisLabel: {
        color: '#666'
      },
      splitLine: {
        lineStyle: {
          color: '#eee'
        }
      }
    },
    series: [
      {
        name: '新增用户',
        type: 'line',
        data: userData,
        smooth: true,
        lineStyle: {
          width: 3,
          color: '#409EFF'
        },
        itemStyle: {
          color: '#409EFF'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(64, 158, 255, 0.5)' },
              { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
            ]
          }
        }
      }
    ],
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    }
  };
  
  // 渲染图表
  userGrowthChart.setOption(option);
  
  // 添加防抖处理窗口大小变化，提高性能
  window.addEventListener('resize', resizeCharts);
};

// 渲染内容分布图表
const renderContentDistributionChart = () => {
  const chartDom = document.getElementById('contentDistributionChart');
  if (!chartDom) return;
  
  // 销毁已有实例
  if (contentDistributionChart) {
    contentDistributionChart.dispose();
  }
  
  // 创建图表实例
  contentDistributionChart = echarts.init(chartDom);
  
  // 获取数据，避免NaN和极端值
  const questionValue = Math.max(10, dashboardData.value.questionCount || 100);
  const answerValue = Math.max(30, dashboardData.value.answerCount || 300);
  const commentValue = Math.max(50, dashboardData.value.commentCount || 500);
  const otherValue = Math.round(Math.random() * 100 + 50);
  
  // 饼图数据和选项
  const option = {
    title: {
      text: '内容分布',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 10,
      top: 'center',
      data: ['问题', '回答', '评论', '其他'],
      textStyle: {
        color: '#666'
      },
      itemWidth: 10,
      itemHeight: 10,
      itemGap: 10
    },
    series: [
      {
        name: '内容数量',
        type: 'pie',
        radius: ['50%', '70%'],
        center: ['60%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '16',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { 
            value: questionValue, 
            name: '问题',
            itemStyle: { color: '#409EFF' }
          },
          { 
            value: answerValue, 
            name: '回答',
            itemStyle: { color: '#67C23A' }
          },
          { 
            value: commentValue, 
            name: '评论',
            itemStyle: { color: '#E6A23C' }
          },
          { 
            value: otherValue, 
            name: '其他',
            itemStyle: { color: '#909399' }
          }
        ]
      }
    ]
  };
  
  // 渲染图表
  contentDistributionChart.setOption(option);
};

// 防抖处理窗口大小变化
let resizeTimer = null;
const resizeCharts = () => {
  if (resizeTimer) {
    clearTimeout(resizeTimer);
  }
  resizeTimer = setTimeout(() => {
    userGrowthChart && userGrowthChart.resize();
    contentDistributionChart && contentDistributionChart.resize();
  }, 100);
};

// 快速审核问题
const handleQuickApprove = async (question) => {
  try {
    await reviewQuestion(question.id, 1);
    ElMessage.success('问题审核通过');
    refreshDashboard();
  } catch (error) {
    console.error('审核问题失败:', error);
    ElMessage.error('审核问题失败');
  }
};

// 监听图表周期变化
watch(userChartPeriod, () => {
  renderUserGrowthChart();
});

// 组件卸载前清理图表实例
onBeforeUnmount(() => {
  if (userGrowthChart) {
    userGrowthChart.dispose();
    userGrowthChart = null;
  }
  if (contentDistributionChart) {
    contentDistributionChart.dispose();
    contentDistributionChart = null;
  }
  window.removeEventListener('resize', resizeCharts);
});

// 初始化
onMounted(() => {
  refreshDashboard();
});

// 暴露方法供父组件调用
defineExpose({
  refreshDashboard
});
</script>

<style scoped>
/* 仪表盘样式 */
.dashboard-panel {
  width: 100%;
}

.overview-card {
  height: 160px;
  transition: all 0.3s ease;
  margin-bottom: 15px;
  border-radius: 8px;
  overflow: hidden;
}

.overview-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 15px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 15px;
}

.card-header .el-icon {
  margin-right: 8px;
  font-size: 20px;
}

.card-content {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 90px;
  padding: 0 15px;
}

.card-value {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 12px;
}

.card-info {
  font-size: 14px;
  color: #909399;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.highlight {
  color: #409EFF;
  font-weight: bold;
  margin-left: 5px;
}

.highlight.up {
  color: #67C23A;
}

.highlight.down {
  color: #F56C6C;
}

.user-card {
  border-top: 3px solid #409EFF;
}

.user-card .el-icon {
  color: #409EFF;
}

.question-card {
  border-top: 3px solid #E6A23C;
}

.question-card .el-icon {
  color: #E6A23C;
}

.answer-card {
  border-top: 3px solid #67C23A;
}

.answer-card .el-icon {
  color: #67C23A;
}

.visit-card {
  border-top: 3px solid #F56C6C;
}

.visit-card .el-icon {
  color: #F56C6C;
}

.chart-row {
  margin-top: 30px;
  margin-bottom: 30px;
}

.chart-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.chart-container {
  height: 350px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px;
}

.pending-tasks-card {
  margin-bottom: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.task-group {
  margin-bottom: 20px;
}

.task-group h4 {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  color: #606266;
  font-size: 16px;
  font-weight: 600;
}

.task-group h4 .el-icon {
  margin-right: 8px;
  color: #E6A23C;
  font-size: 18px;
}

.task-footer {
  margin-top: 10px;
  text-align: right;
}

.task-table-wrapper {
  margin-bottom: 10px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.system-notification-timeline {
  padding: 0 10px;
  max-height: 300px;
  overflow-y: auto;
}

:deep(.el-timeline-item__wrapper) {
  padding-bottom: 15px;
}

:deep(.el-timeline-item__content) {
  color: #606266;
  font-size: 14px;
}

:deep(.el-timeline-item__timestamp) {
  color: #909399;
  font-size: 12px;
}

:deep(.el-timeline-item__node--success) {
  background-color: #67C23A;
}

:deep(.el-timeline-item__node--warning) {
  background-color: #E6A23C;
}

:deep(.el-timeline-item__node--info) {
  background-color: #909399;
}

.header-left {
  display: flex;
  align-items: center;
}

/* 移动端适配 */
@media (max-width: 992px) {
  .chart-container {
    height: 300px;
  }
}

@media (max-width: 768px) {
  .chart-container {
    height: 250px;
  }
  
  .card-value {
    font-size: 28px;
  }
  
  .card-info {
    font-size: 12px;
  }
  
  .task-group h4 {
    font-size: 14px;
  }
}

@media (max-width: 480px) {
  .chart-container {
    height: 200px;
  }
}
</style> 